/**
 * Description:字符转码、加密工具
 * @author huxh
 * @date 2012-01-15
 */
package com.cr.backbone.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class UtilsTranscoding {
	
	private static final char[] numbers = {
		'1','2','3','4','5','6','7','8','9'
	};
	
	private static final char[] words = {
		'a','b','c','d','f','g','h','i','j','k','z'
	};

	//MessageDigest.getInstance(algorithm)
	private static final String SHA = "SHA";
	private static final String MD5 = "MD5";

	/**
	 * 根据MD5算法加密密码
	 * @param password
	 * @return
	 */
	public static String Md5PassWordFormat(String password){
		return messageDigest(password,MD5);
	}
	
	/**
	 * 字符串加密
	 * 1、传送值，转换为：固定长度的哈希值
	 * 2、固定长度的哈希值，根据特定算法转成加密后数字、小写字符组成的密文
	 * @param password
	 * @param algorithm
	 * @return
	 */
	public static String messageDigest(String password,String algorithm){
		try {
			MessageDigest messageDigest = java.security.MessageDigest.getInstance(algorithm);
			byte[] inputs=password.getBytes();
			messageDigest.update(inputs);
			byte[] digest_inputs = messageDigest.digest(inputs);
			outDigest(digest_inputs,algorithm);
			int size = digest_inputs.length;
			char[] results = new char[size*2];
			int i=0;
			for(int j =0;j<size*2;){
				int index;
				int hash=Math.abs(digest_inputs[i]);
				index=hash%9;
				results[j++]=numbers[index];
				index=hash%11;
				results[j++]=words[index];
				i++;
			}
			System.out.println("final:"+ new String(results));
			return new String(results);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return null;
		
	}

	
	private static void outDigest(byte[] digest_inputs,String algorithm) {
//		System.out.println("\tMessageDigest "+"\t "+algorithm+" :\t"+ String.valueOf(inputs) );
		System.out.println("MessageDigest "+"\t "+algorithm+" :\t" );
		System.out.println("size:"+digest_inputs.length );
		System.out.print("\t");
		for(byte i :digest_inputs ){
			System.out.print(" ");
			System.out.print(i);
		}
		System.out.println();
		System.out.println("--------------------------------");
	}



	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		UtilsTranscoding.messageDigest("23", SHA);
		UtilsTranscoding.messageDigest("2", SHA);
		UtilsTranscoding.messageDigest("1", SHA);
		UtilsTranscoding.messageDigest("1", SHA);
		UtilsTranscoding.messageDigest("23", MD5);
		UtilsTranscoding.messageDigest("2", MD5);
		UtilsTranscoding.messageDigest("1", MD5);
		UtilsTranscoding.messageDigest("1", MD5);
		
		for(int i= 0;i<=100;i++)
			System.out.println(i%15);
//		System.out.println(1%2);
//		System.out.println(2%2);
//		System.out.println(3%2);
	}

}
